/*
 * 
 * 
 * 
 */
package com.hboxs.asl.controller.admin;

import com.hboxs.asl.*;
import com.hboxs.asl.Message;
import com.hboxs.asl.entity.*;
import com.hboxs.asl.service.*;
import com.hboxs.asl.util.CodeUtils;
import com.hboxs.asl.util.SettingUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * Controller - 会员
 */
@Controller("adminMemberController")
@RequestMapping("/asl-admin/member")
public class MemberController extends BaseController {

    @Resource(name = "memberServiceImpl")
    private MemberService memberService;
    @Resource(name = "memberAttributeServiceImpl")
    private MemberAttributeService memberAttributeService;
    @Resource(name = "adminServiceImpl")
    private AdminService adminService;
    @Resource(name = "memberCertificationServiceImpl")
    private MemberCertificationService memberCertificationService;
    @Resource(name = "fileServiceImpl")
    private FileService fileService;
    @Resource(name = "productImageServiceImpl")
    private ProductImageService productImageService;
    @Resource(name = "categoryServiceImpl")
    private CategoryService categoryService;
    @Resource(name = "caseServiceImpl")
    private CaseService caseService;
    @Resource(name = "globalConfigServiceImpl")
    private GlobalConfigService globalConfigService;



    /**
     * 检查用户名是否被禁用或已存在
     */
    @RequestMapping(value = "/check_username", method = RequestMethod.GET)
    public
    @ResponseBody
    boolean checkUsername(String username) {
        if (StringUtils.isEmpty(username)) {
            return false;
        }
        return !(memberService.usernameDisabled(username) || memberService.usernameExists(username));
    }

    /**
     * 检查E-mail是否唯一
     */
    @RequestMapping(value = "/check_email", method = RequestMethod.GET)
    public
    @ResponseBody
    boolean checkEmail(String previousEmail, String email) {
        if (StringUtils.isEmpty(email)) {
            return false;
        }
        return memberService.emailUnique(previousEmail, email);
    }

    /**
     * 查看
     */
    @RequestMapping(value = "/view", method = RequestMethod.GET)
    public String view(Long id, ModelMap model) {
        model.addAttribute("memberAttributes", memberAttributeService.findList());
        model.addAttribute("member", memberService.find(id));
        return "/admin/member/view";
    }

    /**
     * 添加
     */
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add(ModelMap model , HttpSession session) {
        session.setAttribute(IMAGE_TYPE, ProductImage.imageType.avator);
        model.addAttribute("categorys" , categoryService.findAll());
        model.addAttribute("point", globalConfigService.getUniqueness().getPoint());
        return "/admin/member/add";
    }

    /**
     * 我的案例
     */
    @RequestMapping(value = "/mycase", method = RequestMethod.GET)
    public String mycase(ModelMap model, HttpSession session, Long id) {
        session.setAttribute(IMAGE_TYPE, ProductImage.imageType.example);
        model.addAttribute("case", caseService.find(id));
        return "/admin/member/case";
    }


    /**
     * 保存
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String save(Member member, Long categoryId, MemberCertification memberCertification, HttpServletRequest request,
                       RedirectAttributes redirectAttributes , HttpSession session) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

        // 资格证书
        List<MultipartFile> qualificationImages = multipartRequest.getFiles("qualificationImage");
        for (Iterator<MultipartFile> iterator = qualificationImages.iterator(); iterator.hasNext(); ) {
            MultipartFile file = iterator.next();
            if (!fileService.isValid(FileInfo.FileType.image, file)) iterator.remove();
        }
        if (qualificationImages.size()!=0) {
            memberCertification.setQualificationImages(productImageService.buildForStringImages(qualificationImages, session.getAttribute(IMAGE_TYPE).toString()));
        }

        // 机构认证
        List<MultipartFile> agencyImages = multipartRequest.getFiles("agencyImage");
        for (Iterator<MultipartFile> iterator = agencyImages.iterator(); iterator.hasNext(); ) {
            MultipartFile file = iterator.next();
            if (!fileService.isValid(FileInfo.FileType.image, file)) iterator.remove();
        }
        if (agencyImages.size()!=0) {
            memberCertification.setAgencyImages(productImageService.buildForStringImages(agencyImages, session.getAttribute(IMAGE_TYPE).toString()));
        }

        Category category = categoryService.find(categoryId);
        if(null != category) member.setCategory(category);

        Setting setting = SettingUtils.get();
        if (member.getPassword().length() < setting.getPasswordMinLength() || member.getPassword().length() > setting.getPasswordMaxLength()) {
            return ERROR_VIEW;
        }
        if (memberService.usernameDisabled(member.getUsername()) || memberService.usernameExists(member.getUsername())) {
            return ERROR_VIEW;
        }
        if (!setting.getIsDuplicateEmail() && memberService.emailExists(member.getEmail())) {
            return ERROR_VIEW;
        }

        member.setUsername(member.getUsername().toLowerCase());
        member.setPassword(DigestUtils.md5Hex(member.getPassword()));
        member.setAmount(new BigDecimal(0));
        member.setIsLocked(false);
        member.setLoginFailureCount(0);
        member.setLockedDate(null);
        member.setRegisterIp(request.getRemoteAddr());
        member.setLoginIp(null);
        member.setLoginDate(null);
        member.setSafeKey(null);
        member.setCart(null);
        member.setOrders(null);
        member.setDeposits(null);
        member.setPayments(null);
        member.setCouponCodes(null);
        member.setReceivers(null);
        member.setReviews(null);
        member.setConsultations(null);
        member.setFavoriteProducts(null);
        member.setProductNotifies(null);
        member.setInMessages(null);
        member.setOutMessages(null);
        member.setIsTop(false);
        memberCertificationService.save(memberCertification);

        member.setMemberCertification(memberCertification);
        memberService.save(member, adminService.getCurrent());
        member.setName(member.getID().toString());
        memberService.update(member);
        addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
        return "redirect:list.htm";
    }

    /**
     * 编辑
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(Long id, ModelMap model, HttpSession session) {
        session.setAttribute(IMAGE_TYPE, ProductImage.imageType.avator);
        model.addAttribute("status", MemberCertification.Status.values());
        model.addAttribute("member", memberService.find(id));
        model.addAttribute("categorys" , categoryService.findAll());
        return "/admin/member/edit";
    }

    /**
     * 更新
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String update(Member member, Long categoryId,  MemberCertification memberCertification, Long memberCertificationId,
                         BigDecimal modifyPoint, BigDecimal modifyBalance, String depositMemo,
                         HttpServletRequest request, RedirectAttributes redirectAttributes, HttpSession session) {
        Setting setting = SettingUtils.get();
        if (member.getPassword() != null && (member.getPassword().length() < setting.getPasswordMinLength() || member.getPassword().length() > setting.getPasswordMaxLength())) {
            return ERROR_VIEW;
        }
        Member pMember = memberService.find(member.getId());
        if (pMember == null) {
            return ERROR_VIEW;
        }
        if (!setting.getIsDuplicateEmail() && !memberService.emailUnique(pMember.getEmail(), member.getEmail())) {
            return ERROR_VIEW;
        }

        if (StringUtils.isEmpty(member.getPassword())) {
            member.setPassword(pMember.getPassword());
        } else {
            member.setPassword(DigestUtils.md5Hex(member.getPassword()));
        }

        Category category = categoryService.find(categoryId);
        if(null != category) {
            member.setCategory(category);
        }

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        // 资格证书
        List<MultipartFile> qualificationImages = multipartRequest.getFiles("qualificationImage");
        for (Iterator<MultipartFile> iterator = qualificationImages.iterator(); iterator.hasNext(); ) {
            MultipartFile file = iterator.next();
            if (!fileService.isValid(FileInfo.FileType.image, file)) iterator.remove();
        }
        if (qualificationImages.size()!=0) {
            memberCertification.getQualificationImages().addAll((productImageService.buildForStringImages(qualificationImages, session.getAttribute(IMAGE_TYPE).toString())));
        }

        // 资格证书
        List<MultipartFile> agencyImages = multipartRequest.getFiles("agencyImage");
        for (Iterator<MultipartFile> iterator = agencyImages.iterator(); iterator.hasNext(); ) {
            MultipartFile file = iterator.next();
            if (!fileService.isValid(FileInfo.FileType.image, file)) iterator.remove();
        }
        if (agencyImages.size()!=0) {
            memberCertification.getAgencyImages().addAll((productImageService.buildForStringImages(agencyImages, session.getAttribute(IMAGE_TYPE).toString())));
        }

        if(memberCertification.getStatus().equals(MemberCertification.Status.passed)){
            member.setCode(CodeUtils.generateCode(member));
            member.setType(Member.Type.teacher);
            if(memberCertification.getPayGanqing() == null) {
                memberCertification.setPayGanqing(BigDecimal.ZERO);
            }
            if(memberCertification.getPayShiye() == null) {
                memberCertification.setPayShiye(BigDecimal.ZERO);
            }
            if(memberCertification.getPayFengshui() == null) {
                memberCertification.setPayFengshui(BigDecimal.ZERO);
            }
            if(memberCertification.getPayOther() == null) {
                memberCertification.setPayOther(BigDecimal.ZERO);
            }
        }else{
            member.setType(Member.Type.member);
            member.setCode(null);
        }

        if (pMember.getIsLocked() && !member.getIsLocked()) {
            member.setLoginFailureCount(0);
            member.setLockedDate(null);
        } else {
            member.setIsLocked(pMember.getIsLocked());
            member.setLoginFailureCount(pMember.getLoginFailureCount());
            member.setLockedDate(pMember.getLockedDate());
        }
        // 处理之前没有关联认证对象的member
        if (memberCertificationId == null) {
            memberCertification.setId(null);
            memberCertification.setMember(pMember);
            memberCertification.setCerType(MemberCertification.CerType.person);
            memberCertificationService.save(memberCertification);
            member.setMemberCertification(memberCertification);
        } else {
            MemberCertification pMemberCertification = memberCertificationService.find(memberCertificationId);
            BeanUtils.copyProperties(memberCertification, pMemberCertification, "id", "merchant");
            pMemberCertification.setMember(pMember);
            memberCertificationService.update(pMemberCertification);
            member.setMemberCertification(pMemberCertification);
        }
        BeanUtils.copyProperties(member, pMember, "token", "background", "username", "amount","bankCards",
                "registerIp", "loginIp", "loginDate", "safeKey",  "deposits", "payments", "couponCodes", "receivers","questionTrades",
                "reviews", "consultations",  "inMessages", "outMessages", "tags", "courseTrades","cases", "essays","courses",
                "favorLives", "watchedLives", "favorAnchors", "questions", "answers", "favorMembers", "earnings");
        memberService.update(pMember, modifyPoint, modifyBalance, depositMemo, adminService.getCurrent());
        addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
        return "redirect:list.htm";
    }

    /**
     * 列表
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(Pageable pageable, ModelMap model,
    String username, String name , String type , MemberCertification.Gender gender , String juese , Date startCreateDate, Date endCreateDate
                       ) {

        List<Filter> fs = pageable.getFilters();

        if(!StringUtils.isEmpty(username)){
            fs.add(Filter.like("username" , "%" + username + "%"));
            model.addAttribute("username" , username);
        }

        if(!StringUtils.isEmpty(name)){
            fs.add(Filter.like("name" , "%" + name + "%"));
            model.addAttribute("name" , name);
        }

        if(gender!=null){
            fs.add(Filter.eq("memberCertification.gender" , gender));
            model.addAttribute("gender" , gender);
        }

        if("teacher".equals(juese)){
            fs.add(Filter.eq("memberCertification.status" , MemberCertification.Status.passed));
            model.addAttribute("juese" , juese);
        }

        if(startCreateDate!=null){
            fs.add(Filter.geDate("createDate", startCreateDate));
            model.addAttribute("startCreateDate" , startCreateDate);
        }

        if(endCreateDate!=null){
            fs.add(Filter.leDate("createDate", endCreateDate));
            model.addAttribute("endCreateDate" , endCreateDate);
        }


        model.addAttribute("page", memberService.findPage(pageable));
        return "/admin/member/list";
    }

    /**
     * 删除
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public
    @ResponseBody
    Message delete(Long[] ids) {
        if (ids != null) {
            for (Long id : ids) {
                Member member = memberService.find(id);
                if (member != null && member.getBalance().compareTo(new BigDecimal(0)) > 0) {
                    return Message.error("admin.member.deleteExistDepositNotAllowed", member.getUsername());
                }
                memberService.update(member);
            }
            memberService.delete(ids);
        }
        return SUCCESS_MESSAGE;
    }

    /**
     * 修改案例
     */
    @RequestMapping(value = "/update_case", method = RequestMethod.POST)
    public String list(Case example) {
        if(example != null) {
            caseService.update(example, "member");
        }
        return "redirect:list.htm";
    }

}